/**
 *
 */
package cn.hg.jfsa.manage.controller.system;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.PasswordKit;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.SessionThreadLocal;
import cn.hg.jfsa.manage.controller.system.validator.AdminValidator;
import cn.hg.jfsa.manage.controller.system.validator.BaseInfoValidator;
import cn.hg.jfsa.manage.controller.system.validator.ChangePasswordValidator;
import cn.hg.jfsa.manage.service.JfsaOrgService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.model.JfsaAdminRole;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.*;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * @author Golly
 *
 */
public class JfsaAdminController extends BaseController {

	@Inject
	private JfsaOrgService orgService;

	/**
	 * 跳转到新增页面
	 */
	public void add() {
		// 创建新记录
		this.setAttr("admin", new JfsaAdmin());
		this.setAttr("orgTree", orgService.getTree());
	}

	/**
	 * 执行分派权限操作
	 */
	@Before(POST.class)
	public void ajaxAssignRole() {
		JfsaAdminRole bean = this.getBean(JfsaAdminRole.class, "adminRole");

		if (null == bean.getId()) {
			bean.save();
		} else {
			if (StrKit.isBlank(bean.getRoleIds())) {
				bean.delete();
			} else {
				bean.update();
			}
		}

		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax删除功能
	 */
	@Before(EvictInterceptor.class)
	@CacheName("jfsaAdmin")
	public void ajaxDel() {
		// 通过页面传入的ID查找到记录
		JfsaAdmin bean = JfsaAdmin.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		// ID为1的管理员非常特殊，不允许删除
		if (1 == bean.getId()) {
			this.renderAjaxFailed("1", "ID为1的管理员不允许删除！");
			return;
		}

		// 更新记录的状态为删除
		bean.setStatus("del").update();

		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax方式取得管理员角色
	 */
	public void ajaxGetAdminRole() {
		JfsaAdmin bean = JfsaAdmin.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		List<Record> roleList = Db.find(
				"SELECT r.id, r.`name`, r.remark, FIND_IN_SET(r.id, ar.role_ids) > 0 AS LAY_CHECKED FROM jfsa_role AS r LEFT JOIN jfsa_admin_role AS ar ON r.status='on' AND ar.admin_id=?",
				bean.getId());

		this.renderJson(new LayuiPage(roleList));
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before({AdminValidator.class, EvictInterceptor.class})
	@CacheName("jfsaAdmin")
	public void ajaxSaveOrUpdate() {
		// 获取页面传入的Bean
		JfsaAdmin bean = this.getBean(JfsaAdmin.class, "admin");

		JfsaAdmin exist = JfsaAdmin.DAO.findFirst("select * from jfsa_admin where account = ? and id <> ?",
				bean.getAccount(), bean.getId());

		if (exist != null) {
			this.renderAjaxFailed("1", "登录名已经存在!请更换其它登录名。");
			return;
		}

		JfsaAdmin currAdmin = SessionThreadLocal.getAdmin();

		String newPassword = this.getPara("newPassword");
		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {
			@Override
			public boolean run() throws SQLException {
				if (null == bean.getId()) {
					String salt = PasswordKit.genSalt();
					String password = PasswordKit.genSecretPassword(salt, bean.getPassword());
					// 初始化数据
					bean.setSalt(salt).setCreatedTime(new Date()).setCreatorId(currAdmin.getId())
							.setPassword(password);

					// 新建记录
					bean.save();
				} else {
					if (1 == bean.getId()) { // ID为1的管理员状态必须为on
						bean.setStatus("on");
					}

					if (StrKit.notBlank(newPassword)) {
						JfsaAdmin admin = JfsaAdmin.DAO.findById(bean.getId());
						bean.setPassword(PasswordKit.genSecretPassword(admin.getSalt(), newPassword));
					}

					// 更新记录
					bean.setEditorId(currAdmin.getId()).setEditedTime(new Date()).update();
				}
				return true;
			}
		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}
	}

	/**
	 * Ajax方式查询
	 */
	@Before(CacheInterceptor.class)
	@CacheName("jfsaAdmin")
	public void ajaxSearch() {
		// 建立查询键值对
		Kv para = Kv.by("account", this.getPara("account")).set("name", this.getPara("name"))
				.set("createdTimeStart", this.getParaToDate("addTimeStart"))
				.set("createdTimeEnd", this.getParaToDate("addTimeEnd")).set("status", this.getPara("status"))
				.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
				.set("sortType", this.getPara("sortType"));

		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("system.findAdmin", para);

		// 执行查询
		Page<JfsaAdmin> page = JfsaAdmin.DAO.paginate(getParaToInt("page", 1), getParaToInt("limit", 10), sqlPara);

		this.setAttr("sortField", this.getPara("sortField"));
		this.setAttr("sortType", this.getPara("sortType"));

		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(page));
	}

	/**
	 * 跳转到分派权限页面
	 */
	@Before(GET.class)
	public void assignRole() {
		JfsaAdmin bean = JfsaAdmin.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		JfsaAdminRole adminRole = JfsaAdminRole.DAO.findFirst("SELECT * FROM jfsa_admin_role WHERE admin_id=?",
				bean.getId());

		this.setAttr("adminRole", adminRole == null ? new JfsaAdminRole() : adminRole);

		this.setAttr("admin", bean);
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit() {
		// 查询目标记录
		this.setAttr("admin", JfsaAdmin.DAO.findById(this.getParaToInt("id")));
		this.setAttr("orgTree", orgService.getTree());
	}

	/**
	 * 跳转到列表页面
	 */
	@Override
	@Before(CacheInterceptor.class)
	@CacheName("jfsaAdmin")
	public void index() {
	}

	/**
	 * 跳转到查看页面
	 */
	@Before(CacheInterceptor.class)
	@CacheName("jfsaAdmin")
	public void view() {
		JfsaAdmin bean = JfsaAdmin.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		this.setAttr("admin", bean);
	}

	@Before(ChangePasswordValidator.class)
	public void changePassword() {
		if (this.isPostRequest()) {
			JfsaAdmin admin = SessionThreadLocal.getAdmin();

			if (!PasswordKit.validatePassword(admin.getSalt(), this.getPara("oldPassword"), admin.getPassword())) {
				this.setAttr("flashMsg", "当前密码不正确！");
				this.keepPara();
				return;
			}

			admin.setPassword(PasswordKit.genSecretPassword(admin.getSalt(), this.getPara("newPassword"))).update();
			this.setAttr("flashMsg", "新密码修改成功！");
		}
	}

	@Before(BaseInfoValidator.class)
	public void baseInfo() {
		JfsaAdmin admin = SessionThreadLocal.getAdmin();
		this.set("admin", admin);
		if (this.isPostRequest()) {
			JfsaAdmin newAdmin = this.getBean(JfsaAdmin.class, "admin");

			// 处理密码
			if(!this.isParaBlank("newPassword")){
				admin.setPassword(PasswordKit.genSecretPassword(admin.getSalt(), this.getPara("newPassword")));
			}

			admin.setName(newAdmin.getName()).setTelephone(newAdmin.getTelephone())
					.setMobilePhone(newAdmin.getMobilePhone()).setEmail(newAdmin.getEmail())
					.update();

			SessionThreadLocal.setAdmin(admin);
			this.set("flashMsg", "基本资料修改成功！");
		}
	}
}
